/**
 * Created by user on 2020/3/2.
 */

function onInput(el, ele, binding, vnode) {
    function handler() {
        const oldValue = ele.value;
        if (!oldValue) {
            return;
        }

        let value;
        if (binding.modifiers.positive && binding.modifiers.int) {
            value = oldValue.replace(/[^0-9]/g, '');
        } else if (binding.modifiers.int) {
            value = oldValue.replace(/[^0-9]/g, '');
        } else if (binding.modifiers.positive) {
            value = oldValue.replace(/[^0-9]/g, '');
        } else {
            value = oldValue.replace(/[^0-9]/g, '');
        }

        if (value != oldValue) {
            ele.value = value;

            if (vnode.componentInstance) {
                vnode.componentInstance.$emit('input', value)
            } else {
                vnode.elm.dispatchEvent(new CustomEvent('input', value))
            }
        }
    }

    return handler;
}

/**
 * 限制输入数字，只能输入数字
 * 支持int、positive另种修饰符
 */
export default {'install': Vue => {
    Vue.directive("number-input", {
        bind: function (el, binding, vnode) {
            const ele = el.tagName === 'INPUT' ? el : el.querySelector('input');

            if (ele) {
                if (!ele.style.textAlign) {
                    // ele.style.textAlign = 'right';
                    /**
                    if (window.getComputedStyle) {
                        if (!window.getComputedStyle(ele).textAlign) {
                            //ele.style.textAlign = 'right';
                        }

                    } **/
                }

                const handler = onInput(el, ele, binding, vnode);
                ele['number-input-handler'] = handler;
                ele.addEventListener('input', handler);
            }
        },
        unbind: function (el, binding, vnode) {
            const ele = el.tagName === 'INPUT' ? el : el.querySelector('input');
            if (ele && ele['number-input-handler']) {
                ele.removeEventListener('input', ele['number-input-handler']);
                ele['number-input-handler'] = null;
            }
        }
    });

}}
